package com.library.controller;/*
 *@author lzg
 *@data 2020/11/29
 */

import com.library.entity.Admin;
import com.library.entity.BorrowRecode;
import com.library.entity.Reader;
import com.library.service.AdminServer;
import com.library.service.impl.AdminServerImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin")
public class AdminServlet extends HttpServlet {
    private AdminServer adminServer = new AdminServerImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int time = session.getMaxInactiveInterval();
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null || time<=0){
            req.getRequestDispatcher("login.jsp").forward(req, resp);
            return;
        }

        String method = req.getParameter("method");
        if (method==null){
            method = "findAll";
        }
        String page = req.getParameter("page");
        int pageIndex = 1;
        if (page != null){
            pageIndex = Integer.parseInt(page);
        }
        int limitNum = 6;//每页多少行
        List<BorrowRecode> borrowRecodeList = null;
        switch (method){
            case "handle":
                String idStr = req.getParameter("id");
                int id = Integer.parseInt(idStr);
                String stateStr = req.getParameter("state");
                int state = Integer.parseInt(stateStr);
                adminServer.UpdateBorrowApproval(id, state);

                borrowRecodeList = adminServer.findAllApproval((pageIndex*limitNum)-limitNum,limitNum);
                //每页数量
                req.setAttribute("dataPrePage", limitNum);
                //当前页数
                req.setAttribute("currentPage", pageIndex);
                //总页数
                req.setAttribute("pages", adminServer.getPageSize(limitNum));
                req.setAttribute("list", borrowRecodeList);
                req.getRequestDispatcher("admin.jsp").forward(req, resp);
                break;
            case "findAll":
                borrowRecodeList = adminServer.findAllApproval((pageIndex*limitNum)-limitNum,limitNum);
                //每页数量
                req.setAttribute("dataPrePage", limitNum);
                //当前页数
                req.setAttribute("currentPage", pageIndex);
                //总页数
                req.setAttribute("pages", adminServer.getPageSize(limitNum));
                req.setAttribute("list", borrowRecodeList);
                req.getRequestDispatcher("admin.jsp").forward(req, resp);
                break;
        }
    }
}
